//
//  DestinationCountryViewController.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DestinationCountryViewController.h"
#import "DestinationNoticeViewController.h"
#import "DestinationTripViewController.h"
#import "DestinationTripObject.h"
#import "DesDetailPlaceTableViewCell.h"
#import "DesPlaceViewController.h"
#import "DestinationPlaceViewController.h"
#import "DestinationDetailObject.h"
#import "DesTripPhotosVController.h"
#import "DesPlacePhotoObject.h"

#import "MBProgressHUD.h"

#define TABLEREUSE @"placeViewCellReuse"

@interface DestinationCountryViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain)DestinationTripObject *tripObject;
@property (nonatomic, retain)DestinationDetailObject *detailObject;
@property (nonatomic, retain)UIImageView *imgProfile;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *phontArr;
@property (nonatomic, retain)NSMutableArray *modelArr;
@property (nonatomic, retain)UITableView *placeTableView;
@property (nonatomic, retain)NSMutableArray *photosArr;
@property (nonatomic, retain)UIImageView *visitedPicView;
@property (nonatomic, retain)UILabel *visitedLabel;
@property (nonatomic, retain)UIImageView *wish_to_goPicView;
@property (nonatomic, retain)UILabel *wish_to_goLabel;

@property (nonatomic, retain)MBProgressHUD *progressHUD;

@end

@implementation DestinationCountryViewController

- (void)dealloc
{
    [_sendId release];
    [_sendType release];
    [_tripObject release];
    [_detailObject release];
    [_imgProfile release];
    [_scrollView release];
    [_tableView release];
    [_phontArr release];
    [_modelArr release];
    [_placeTableView release];
    [_photosArr release];
    [_visitedLabel release];
    [_visitedPicView release];
    [_wish_to_goPicView release];
    [_wish_to_goLabel release];
    [_progressHUD release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    
    [self handlePhotoData];
    [self setupView];

}
# pragma mark - 建立视图
- (void)setupView
{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];

    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
    self.scrollView.delegate = self;
    [_scrollView release];
    
    self.imgProfile = [[UIImageView alloc] init];
    self.imgProfile.frame = CGRectMake(0, 0, VIEW_WIDTH, (VIEW_HEIGHT) / 3);
    self.imgProfile.contentMode = UIViewContentModeScaleAspectFill;
    self.imgProfile.clipsToBounds = YES;
    self.imgProfile.userInteractionEnabled = YES;
    [_imgProfile setImageWithURL:[NSURL URLWithString:[[self.phontArr objectAtIndex:0] objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    [self.scrollView insertSubview:_imgProfile atIndex:0];
    [_imgProfile release];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_imgProfile addGestureRecognizer:tapRecognizer];
    [tapRecognizer release];
    
    CGRect frame = _scrollView.frame;
    frame.origin.y = (VIEW_HEIGHT + 64 + 49) / 3;
    _scrollView.frame = frame;
    
    
    self.visitedPicView = [[UIImageView alloc] init];
    [_scrollView addSubview:_visitedPicView];
    [_visitedPicView release];
    
    self.visitedLabel = [[UILabel alloc] init];
    [self.scrollView addSubview:_visitedLabel];
    [_visitedLabel release];
    
    self.wish_to_goPicView = [[UIImageView alloc] init];
    [_scrollView addSubview:_wish_to_goPicView];
    [_wish_to_goPicView release];
    
    self.wish_to_goLabel = [[UILabel alloc] init];
    [_scrollView addSubview:_wish_to_goLabel];
    [_wish_to_goLabel release];
    
    // 游记 按钮
    UIButton *tripButton = [UIButton buttonWithTitle:@"游记" frame:CGRectMake(VIEW_WIDTH / 5 , (VIEW_HEIGHT) / 3 + 3, VIEW_WIDTH / 5 + 10, VIEW_WIDTH / 11) target:self action:@selector(tripButtonAction:)];
    tripButton.layer.cornerRadius = VIEW_WIDTH / 22;
    tripButton.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    [self.scrollView addSubview:tripButton];

    // 须知 按钮
    UIButton *noticeButton = [UIButton buttonWithTitle:@"须知" frame:CGRectMake(VIEW_WIDTH * 3 / 5 - 10, (VIEW_HEIGHT) / 3 + 3, VIEW_WIDTH / 5 + 10, VIEW_WIDTH / 11) target: self action:@selector(noticeButtonAction:)];
    noticeButton.layer.cornerRadius = VIEW_WIDTH / 22;
    noticeButton.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    [self.scrollView addSubview:noticeButton];

    // 小分区 标题
    CGFloat underHeight = noticeButton.frame.origin.y + noticeButton.frame.size.height;
    UILabel *placeHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, underHeight + 3, VIEW_WIDTH - 2 * 10, 30)];
    placeHeaderLabel.text = @"- - - - -   推荐景点  - - - - -";
    placeHeaderLabel.textColor = [UIColor whiteColor];
    placeHeaderLabel.layer.cornerRadius = 10;
    placeHeaderLabel.clipsToBounds = YES;
    placeHeaderLabel.font = [UIFont systemFontOfSize:19];
    placeHeaderLabel.backgroundColor = [UIColor colorWithRed:51.0 / 255.0 green:51.0 / 255.0 blue:102.0 / 255.0 alpha:0.8];
    placeHeaderLabel.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:placeHeaderLabel];
    [placeHeaderLabel release];
    
    // 推荐景点列表(tableView)
    self.placeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, placeHeaderLabel.frame.origin.y + placeHeaderLabel.frame.size.height, VIEW_WIDTH, (VIEW_HEIGHT) ) style:UITableViewStylePlain];
    _placeTableView.delegate = self;
    _placeTableView.dataSource = self;
    _placeTableView.scrollEnabled = NO;
    [self.placeTableView registerClass:[DesDetailPlaceTableViewCell class] forCellReuseIdentifier:TABLEREUSE];
    _placeTableView.separatorStyle = NO;
    [self.scrollView addSubview:self.placeTableView];
    [_placeTableView release];
    
    // 更多景点 按钮
    UIButton *moreButton = [UIButton buttonWithTitle:@"- - - - -   更多景点  - - - - -" frame:CGRectMake(10, underHeight + placeHeaderLabel.frame.size.height + (VIEW_HEIGHT) + 5, VIEW_WIDTH  - 10 * 2, 30) target:self action:@selector(moreButtonAction:)];
    moreButton.layer.cornerRadius = 10;
    moreButton.backgroundColor = [UIColor colorWithRed:51.0 / 255.0 green:51.0 / 255.0 blue:102.0 / 255.0 alpha:0.8];
    [self.scrollView addSubview:moreButton];
    
    //转菊花
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.placeTableView];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
}


# pragma mark - 给视图分配大小
- (void)makeViewsFrame
{
    self.title = self.tripObject.name;
    
    [_imgProfile setImageWithURL:[NSURL URLWithString:[[self.photosArr objectAtIndex:0] photo]]];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_imgProfile addGestureRecognizer:tapRecognizer];
    [tapRecognizer release];
    
    
    _visitedPicView.frame = CGRectMake(10, (VIEW_HEIGHT + 64 + 49) * 4 / 5 / 3 + 5, 3, (VIEW_HEIGHT + 64 + 49) / 5 / 3 / 2 - 10);
    _visitedPicView.image = [UIImage imageNamed:@"ticket_@2x.png"];
    _visitedPicView.layer.cornerRadius = (VIEW_WIDTH - (10 + 10) * 2) / 2;
    
    _visitedLabel.frame = CGRectMake(10 + 10, (VIEW_HEIGHT + 64 + 49) * 4 / 5 / 3, VIEW_WIDTH - (10 + 10) * 2, (VIEW_HEIGHT + 64 + 49) / 5 / 3 / 2);
    _visitedLabel.text = [NSString stringWithFormat:@"%@ 人去过", [_detailObject.visited_count stringValue]];
    _visitedLabel.textColor = [UIColor whiteColor];
    _visitedLabel.font = [UIFont systemFontOfSize:12];
    
    _wish_to_goPicView.frame = CGRectMake(10, _visitedLabel.frame.origin.y + _visitedLabel.frame.size.height + 5, 3, (VIEW_HEIGHT + 64 + 49) / 5 / 3 / 2 - 10);
    _wish_to_goPicView.image = [UIImage imageNamed:@"ticket_@2x.png"];
    _wish_to_goPicView.layer.cornerRadius = (VIEW_WIDTH - (10 + 10) * 2) / 2;
    
    _wish_to_goLabel.frame = CGRectMake(10 + 10, _visitedLabel.frame.origin.y + _visitedLabel.frame.size.height, VIEW_WIDTH - (10 + 10) * 2, (VIEW_HEIGHT + 64 + 49) / 5 / 3 / 2);
    _wish_to_goLabel.text = [NSString stringWithFormat:@"%@ 人想去", [_detailObject.wish_to_go_count stringValue]];
    _wish_to_goLabel.textColor = [UIColor whiteColor];
    _wish_to_goLabel.font = [UIFont systemFontOfSize:12];
    
    self.scrollView.frame = self.view.bounds;
    self.scrollView.contentSize = CGSizeMake(VIEW_WIDTH, self.imgProfile.frame.size.height + VIEW_WIDTH / 10 + 30 + self.placeTableView.bounds.size.height + 15 + 30);
}
#pragma mark - 上端图片拉伸放大方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat yOffset   = self.scrollView.contentOffset.y;
    if (yOffset < 0) {
        CGFloat factor = ((ABS(yOffset)+(VIEW_HEIGHT + 64 + 49) / 3)*VIEW_WIDTH)/((VIEW_HEIGHT + 64 + 49) / 3);
        CGRect f = CGRectMake(-(factor-VIEW_WIDTH)/2, 0, factor, (VIEW_HEIGHT + 64 + 49) / 3 + ABS(yOffset));
        self.imgProfile.frame = f;
        _imgProfile.center = CGPointMake(_imgProfile.center.x, _imgProfile.center.y - ABS(yOffset));
        
    }
}

#pragma mark - 左侧返回按钮
- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - tableView 协议方法们
// cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.phontArr.count > 4) {
        return 4;
    } else {
        return self.phontArr.count;
    }
}
// 给 cell 赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DesDetailPlaceTableViewCell *placeCell = [tableView dequeueReusableCellWithIdentifier:TABLEREUSE];
    placeCell.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    placeCell.selectionStyle = UITableViewCellSelectionStyleNone;
    placeCell.placeDetailObject = [self.phontArr objectAtIndex:indexPath.row];
    return placeCell;
}
// 每个 cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 4;
}
// push 下一个页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationPlaceViewController *destinationPlaceVC = [[DestinationPlaceViewController alloc] init];
    DestinationDetailObject *detailObj = [self.phontArr objectAtIndex:indexPath.row];
    destinationPlaceVC.placeSendID = detailObj.idNumber;
    destinationPlaceVC.placeSendType = detailObj.typeNumber;
    [self.navigationController pushViewController:destinationPlaceVC animated:YES];
    [destinationPlaceVC release];
}


#pragma mark - 数据解析
- (void)handleData
{
    NSString *urlStr =[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/", self.sendType, self.sendId];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTrip", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        self.modelArr = [NSMutableArray array];
        self.photosArr = [NSMutableArray array];
        self.tripObject = [[DestinationTripObject alloc] initWithDic:responseObject];
        [self.modelArr addObject:_tripObject];
        NSMutableArray *hottest_palcesArr = [responseObject objectForKey:@"hottest_places"];
        for (NSMutableDictionary *dic in hottest_palcesArr) {
            DesPlacePhotoObject *placePhtotObj = [[DesPlacePhotoObject alloc] initWithDic:dic];
            [_photosArr addObject:placePhtotObj];
            [placePhtotObj release];
        }
        [self makeViewsFrame];
        [_tripObject release];
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        self.modelArr = [NSMutableArray array];
        self.photosArr = [NSMutableArray array];
        self.tripObject = [[DestinationTripObject alloc] initWithDic:resultID];
        [self.modelArr addObject:_tripObject];
        NSMutableArray *hottest_palcesArr = [resultID objectForKey:@"hottest_places"];
        for (NSMutableDictionary *dic in hottest_palcesArr) {
            DesPlacePhotoObject *placePhtotObj = [[DesPlacePhotoObject alloc] initWithDic:dic];
            [_photosArr addObject:placePhtotObj];
            [placePhtotObj release];
        }
        [self makeViewsFrame];
        [_tripObject release];
        [self.tableView reloadData];
        static NSInteger i = 1;
        if (1 == i) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        i++;
    }];
}
#pragma mark - 推荐景点 数据解析
- (void)handlePhotoData
{
    NSString *urlStr =[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/pois/sights/?sort=default&start=0&latitude=38.883890&longitude=121.545445", self.sendType, self.sendId];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripCountrySelectPhoto", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *photoArr = [NSMutableArray array];
        photoArr = [responseObject objectForKey:@"items"];
        self.phontArr = [NSMutableArray array];
        for (NSMutableDictionary *photoDic in photoArr) {
            self.detailObject = [[DestinationDetailObject alloc] initWithDic:photoDic];
            [self.phontArr addObject:_detailObject];
            [_detailObject release];
        }
        [self handleData];
        [_progressHUD removeFromSuperview];
        [self.placeTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        self.phontArr = [NSMutableArray array];
        NSMutableArray *photoArr = [NSMutableArray array];
        photoArr = [resultID objectForKey:@"items"];
        for (NSMutableDictionary *photoDic in photoArr) {
            self.detailObject = [[DestinationDetailObject alloc] initWithDic:photoDic];
            [self.phontArr addObject:_detailObject];
            [_detailObject release];
        }
        [self.placeTableView reloadData];
    }];
}


//--------- 页面上端图片 点击手势
- (void)tapAction:(UITapGestureRecognizer *)tap
{

    DesTripPhotosVController *photosVC = [[DesTripPhotosVController alloc] init];
    photosVC.photosSendId = self.sendId;
    photosVC.photosSendType = self.sendType;
    NSLog(@"<><><  点击  <><>>><");
    [self.navigationController  pushViewController:photosVC animated:YES];
    [photosVC release];
    
}
//---------   游记按钮  方法
- (void)tripButtonAction:(UIButton *)button
{
    DestinationTripViewController *tripViewController = [[DestinationTripViewController alloc] init];
    tripViewController.tripsSendId = self.sendId;
    tripViewController.tripsSendType = self.sendType;
    [self.navigationController pushViewController:tripViewController animated:YES];
    [tripViewController release];
}
//--------- 须知按钮  方法
- (void)noticeButtonAction:(UIButton *)button
{
    DestinationNoticeViewController *noticeViewController = [[DestinationNoticeViewController alloc] init];
    noticeViewController.noticeSendId = self.sendId;
    noticeViewController.noticeSendType = self.sendType;
    [self.navigationController pushViewController:noticeViewController animated:YES];
    [noticeViewController release];

}
//---------- 更多推荐按钮  方法
- (void)moreButtonAction:(UIButton *)button
{
    DesPlaceViewController *placeController = [[DesPlaceViewController alloc] init];
    [self.navigationController pushViewController:placeController animated:YES];
    placeController.sendPlaceId = self.sendId;
    placeController.sendPlaceType = self.sendType;
//    placeController.hidesBottomBarWhenPushed = YES;
    [placeController release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
